<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\BaseModel;
use App\Models\Trade;
use App\Models\TradeCate;

class TradeService extends BaseService
{
    public function list($cateId)
    {
        // 设置对象
        $model = Trade::query();
        // 分类
        $model = $model->where('cate_id', $cateId);
        // 状态
        $model = $model->where('status', BaseModel::STATUS_ENABLE);
        // 获取列表
        $list = $model
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->get(['id', 'trade_name'])
            ->toArray();

        return $list;
    }

    /**
     * 商务详情
     * @param $tradeId
     * @return array
     * @throws BusinessException
     */
    public function detail($tradeId)
    {
        // 获取数据
        $data = Trade::query()->where('id', $tradeId)->first();
        if (!$data) {
            $this->throwBusinessException('商务不存在');
        }
        $data->increment('views');
        $data = $data->toArray();

        $data['cate_name'] = TradeCate::query()->where('id', $data['cate_id'])->value('cate_name');
        $data['trade_img'] = storage($data['trade_img']);
        $data['trade_details'] = json_decode($data['trade_details'], true);
        return $data;
    }
}
